//
//  TGChoosePhotoView.m
//  TongGuanLease
//
//  Created by 张奇 on 2022/4/20.
//

#import "TGChoosePhotoView.h"
#import "TGChoosePhotoCell.h"
#import "ZFImagePicker.h"
#import "TGUploadImgTool.h"
#import "MBProgressHUD+RY.h"
#import "TGUrlInfoModel.h"
#import "UIImage-Extension.h"
#import "TGGaodeLocation.h"
#import "TGPreviewFileView.h"

@interface TGChoosePhotoView()<UICollectionViewDataSource, UICollectionViewDelegate, TGChoosePhotoCellDelegate>
@property (strong, nonatomic) UICollectionView *collectionView;

@property (nonatomic, strong) NSMutableArray *imageArray, *imageAssetsArray;
@property (nonatomic, strong) NSMutableArray *imageUrlInfoArray;
@property (nonatomic, strong) NSArray *filPathArray;

@property (nonatomic, strong) TGUploadImgTool *uploadTool;
@end

@implementation TGChoosePhotoView

- (void)awakeFromNib {
    [super awakeFromNib];
    self.backgroundColor = UIColorForBackground;
    if (self.maxCount == 0) {
        self.maxCount = 100;
    }
    [self setupUI];
}

- (instancetype)initWithMaxCount:(NSInteger)maxCount
                 uploadImageType:(UploadImageType)uploadImageType
                        delegate:(id<TGChoosePhotoViewDelegate>)delegate {
    if (self = [super init] ) {
        self.backgroundColor = UIColorForBackground;
        self.maxCount = (maxCount==0? 100:maxCount);
        self.delegate = delegate;
        self.uploadImageType = uploadImageType;
        [self setupUI];
    }
    return self;
}

- (void)setupUI {
    self.filPathArray = @[@"USER_SERVICE", @"EQUIPMENT_SERVICE", @"SETTLEMENT_SERVICE", @"CRM_SERVICE", @"CONTRACT_SERVICE", @"ASSETS_SERVICE", @"SYSTEM_SERVICE", @"WORK_ORDER_SERVICE", @"NCC_AGGREGATION_SERVICE", @"WORKFLOW_SERVICE", @"THIRD_PARTY_SERVICE", @"RULE_ENGINE_SERVICE", @"SCHEDULE_SERVICE", @"ANALYSIS_SERVICE"];
    
    UIView *contentView = [[UIView alloc] init];
    [self addSubview:contentView];
    [contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsZero);
    }];
    
    [contentView addSubview:self.collectionView];
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsZero);
    }];
    
    [self.collectionView reloadData];
}

- (void)setSelectImageUrlInfoArray:(NSArray<TGUrlInfoModel *> *)selectImageUrlInfoArray {
    _selectImageUrlInfoArray = selectImageUrlInfoArray;
    self.imageUrlInfoArray = [NSMutableArray arrayWithArray:selectImageUrlInfoArray];
    NSMutableArray *urlArray = [NSMutableArray array];
    for (TGUrlInfoModel *userInfoModel in selectImageUrlInfoArray) {
//        NSString *urlStringUTF8 = [userInfoModel.url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        [urlArray addObject:userInfoModel.fullPath];
    }
    self.imageArray = urlArray;
    [self.collectionView reloadData];
}

#pragma mark - UICollectionViewDataSource, UICollectionViewDelegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (self.maxCount >0 && self.imageArray.count >= self.maxCount) {
        return self.imageArray.count;
    } else {
        return self.imageArray.count+1;
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    TGChoosePhotoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"TGChoosePhotoCell" forIndexPath:indexPath];
    cell.delegate = self;
    cell.row = indexPath.item;
    if (indexPath.row == self.imageArray.count) {
        [cell.photoBtn setImage:[UIImage imageNamed:@"workBtnch_addPic"] forState:UIControlStateNormal];
        cell.delectBtn.hidden = YES;
    } else {
        if ([self.imageArray[indexPath.row] isKindOfClass:[UIImage class]]) {
            [cell.photoBtn setImage:self.imageArray[indexPath.row] forState:UIControlStateNormal];
        } else if ([self.imageArray[indexPath.row] isKindOfClass:[NSString class]]) {
            NSString *imgUrl = self.imageArray[indexPath.row];
            if (![imgUrl containsString:@"http"]) {
                imgUrl = StringFormat(PhotoPrefixURL, imgUrl);;
            }
            NSURL *url = [NSURL URLWithString:imgUrl];
            [cell.photoBtn setImageWithURL:url forState:UIControlStateNormal placeholder:kImage(@"common_placehoder")];
        }
        cell.delectBtn.hidden = NO;
    }
    return cell;
}
#pragma mark -
-(void)btnClick:(NSInteger)section Index:(NSInteger)row {
    if (row == self.imageArray.count) {
        //添加图片
        if (self.imageArray.count>=self.maxCount) {
            return;
        }
        [self beginChoosePhoto];
    } else {
        //预览图片
        NSMutableArray *tem = [NSMutableArray arrayWithCapacity:self.imageArray.count];
        for (int i=0; i<self.imageArray.count; i++) {
            if ([self.imageArray[i] isKindOfClass:[PHAsset class]]) {
                [tem addObject:GetDictForPreviewPhoto(self.imageArray[i], ZLPreviewPhotoTypePHAsset)];
            } else if ([self.imageArray[i] isKindOfClass:[NSString class]]) {
                NSString *imgUrl = self.imageArray[i];
                if (![imgUrl containsString:@"http"]) {
                    imgUrl = StringFormat(PhotoPrefixURL, imgUrl);
                }
                NSString *urlStringUTF8 = [imgUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                [tem addObject:GetDictForPreviewPhoto([NSURL URLWithString:urlStringUTF8], ZLPreviewPhotoTypeURLImage)];
            } else if ([self.imageArray[i] isKindOfClass:[UIImage class]]) {
                [tem addObject:GetDictForPreviewPhoto(R(self.imageArray[i]), ZLPreviewPhotoTypeUIImage)];
            }
        }
        [[TGGlobalSharedInstance photoActionSheet:self.getCurrentVC] previewPhotos:tem index:row hideToolBar:YES complete:^(NSArray * _Nonnull photos) {
            NSLog(@"%@", photos);
        }];
    }
}

-(void)deleteBtnClick:(NSInteger)section Index:(NSInteger)row {
    [self.imageArray removeObjectAtIndex:row];
    if (self.imageAssetsArray.count > 0 && row <= (self.imageAssetsArray.count-1)) {
        [self.imageAssetsArray removeObjectAtIndex:row];
    }
    [self.imageUrlInfoArray removeObjectAtIndex:row];
    [self.collectionView reloadData];
    if ([self.delegate respondsToSelector:@selector(tgChoosePhotoViewDidSelectImgArray:imgUrlInfoArray:)]) {
        [self.delegate tgChoosePhotoViewDidSelectImgArray:self.imageArray imgUrlInfoArray:self.imageUrlInfoArray];
    }
}


- (void)beginChoosePhoto {
    
    [TGGlobalSharedInstance cameraOrLibrarySelectVC:self.getCurrentVC maxSelectCount:self.maxCount videoNumber:0 isAddWaterImage:self.isAddWaterImage selectAssets:self.imageAssetsArray success:^(NSInteger type, UIImage * _Nonnull image, NSURL * _Nonnull videoUrl, NSArray<UIImage *> * _Nonnull images, NSArray<PHAsset *> * _Nonnull assets, BOOL isOriginal) {

        if (self.isAddWaterImage) {
            //添加水印
            WEAK
            [[TGGaodeLocation shareInstance] reGeocodeAction:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {
                STRONG
                NSMutableArray *resultImages = [NSMutableArray array];
                if (regeocode) {
                    NSString *waterContent = [NSString stringWithFormat:@"%@\n%@", regeocode.formattedAddress, [[NSDate date] getDateStringYMDHMS]];
                    UIImage *resultImage = [UIImage watermarkImage:image withName:waterContent];
                    [resultImages addObject:resultImage];
                } else {
                    [resultImages addObject:image];
                }
                [self uploadImgsAndCallBack:resultImages];
            }];
         
        } else {
            
            [TGGCD executeMainOpeation:^{
                
                NSMutableArray *resultImages = [NSMutableArray array];
                NSMutableArray *resultAssets = [NSMutableArray array];
                if (type == 0 && image) {
                    //拍照
                    [resultImages addObject:image];
                } else {
                    //选取
                    //先去重
                    for (int i = 0; i < assets.count; i++) {
                        PHAsset *currtAsset = assets[i];
                        if (![self.imageAssetsArray containsObject:currtAsset]) {
                            [resultImages addObject:images[i]];
                            [resultAssets addObject:currtAsset];
                        }
                    }
                }
                [self updateImagePhotos:resultImages finish:^(NSArray <TGUrlInfoModel *>*imageInfoArray) {
                    for (int i = 0; i<resultImages.count; i++) {
                        if (self.imageUrlInfoArray.count < self.maxCount) {
                            //小于最大数量，可添加，否则忽略
                            [self.imageArray addObject:resultImages[i]];
                            if (assets.count > 0) {
                                [self.imageAssetsArray addObject:resultAssets[i]];
                            }
                            [self.imageUrlInfoArray addObject:imageInfoArray[i]];
                        }
                    }
                    //                self.imageUrlInfoArray = [NSMutableArray arrayWithArray:imageInfoArray];
                    [self.collectionView reloadData];
                    if ([self.delegate respondsToSelector:@selector(tgChoosePhotoViewDidSelectImgArray:imgUrlInfoArray:)]) {
                        [self.delegate tgChoosePhotoViewDidSelectImgArray:self.imageArray imgUrlInfoArray:self.imageUrlInfoArray];
                    }
                }];
                
                
            }];
        }
        
    }];
    
}

- (void)uploadImgsAndCallBack:(NSArray <UIImage *> *)resultImages {
    [self updateImagePhotos:resultImages finish:^(NSArray <TGUrlInfoModel *>*imageInfoArray) {
        for (int i = 0; i<resultImages.count; i++) {
            if (self.imageUrlInfoArray.count < self.maxCount) {
                //小于最大数量，可添加，否则忽略
                [self.imageArray addObject:resultImages[i]];
                [self.imageUrlInfoArray addObject:imageInfoArray[i]];
            }
        }
        
        [self.collectionView reloadData];
        if ([self.delegate respondsToSelector:@selector(tgChoosePhotoViewDidSelectImgArray:imgUrlInfoArray:)]) {
            [self.delegate tgChoosePhotoViewDidSelectImgArray:self.imageArray imgUrlInfoArray:self.imageUrlInfoArray];
        }
    }];
}

- (void)updateImagePhotos:(NSArray <UIImage *> *)images finish:(ComplentValueBlock)finish {
    
//    MBProgressHUD *hud = [MBProgressHUD showMessage:@"上传中..." toView:self.getCurrentVC.view];
    MBProgressHUD *hud = [MBProgressHUD showMessage:@"上传中..." toView:[[UIApplication sharedApplication] keyWindow]];
    NSString *uploadImageTypeStr = self.filPathArray[self.uploadImageType];
    if (EmptyCheck(uploadImageTypeStr)) {
        [TGProgressHUD showHUDTip:@"请完善上传类型"];
    }
    [self.uploadTool uploadImgWithFilePath:uploadImageTypeStr imgArray:images complemention:^(NSString * _Nonnull progressStr, NSError * _Nullable error, BOOL isFinished, NSArray<TGUrlInfoModel *> * _Nullable imageInfoArray) {
        NSLog(@"-main---%@-----%d", progressStr, isFinished);
        if (error) {
            [TGGCD executeMainOpeation:^{
                hud.label.text = @"保存失败";
                [hud hideAnimated:YES];
            }];
            return;
        }
        [TGGCD executeMainOpeation:^{
            hud.label.text = [NSString stringWithFormat:@"上传中 %@", progressStr];
        }];
        if (isFinished) {
            [TGGCD executeMainOpeation:^{
                [hud hideAnimated:YES];
            }];
            //上传结束，开始回调
            if (finish) {
                finish(imageInfoArray);
            }
        }
        
    }];
 
}

+ (void)updateImagePhotos:(NSArray <UIImage *> *)images finish:(ComplentValueBlock)finish {
    TGChoosePhotoView *choosePhotoView = [[TGChoosePhotoView alloc] initWithMaxCount:1 uploadImageType:UploadImageType_CONTRACT_SERVICE delegate:nil];
    [choosePhotoView updateImagePhotos:images finish:finish];
}


- (UICollectionView *)collectionView {
    if (!_collectionView) {
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        CGFloat width = SCREEN_WIDTH-TableViewSpace*2;
        CGFloat itemWH = ceil((width-TableViewSpace*3.0)/4.0);
        
        flowLayout.itemSize = CGSizeMake(itemWH, itemWH);
        flowLayout.minimumLineSpacing = TableViewSpace;
        flowLayout.minimumInteritemSpacing = RatioWidth(10);
        flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:flowLayout];
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        [_collectionView registerNib:[UINib nibWithNibName:@"TGChoosePhotoCell" bundle:nil] forCellWithReuseIdentifier:@"TGChoosePhotoCell"];
        _collectionView.backgroundColor = UIColorWhite;
        _collectionView.alwaysBounceHorizontal = NO;
        _collectionView.scrollEnabled = NO;
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.showsHorizontalScrollIndicator = NO;
    }
    return _collectionView;
}

- (NSMutableArray *)imageArray {
    if (!_imageArray) {
        _imageArray = [NSMutableArray array];
    }
    return _imageArray;
}

- (NSMutableArray *)imageAssetsArray {
    if (!_imageAssetsArray) {
        _imageAssetsArray = [NSMutableArray array];
    }
    return _imageAssetsArray;
}

- (NSMutableArray *)imageUrlInfoArray {
    if (!_imageUrlInfoArray) {
        _imageUrlInfoArray = [NSMutableArray array];
    }
    return _imageUrlInfoArray;
}

- (TGUploadImgTool *)uploadTool {
    if (!_uploadTool) {
        _uploadTool = [[TGUploadImgTool alloc] init];
    }
    return _uploadTool;
}

@end
